import React, { act } from "react";
import { Space, Tag } from 'antd'
import { useSelector ,useDispatch} from 'react-redux'
import { closeTab ,setCurrrentMenu} from "../../store/reducers/tab";
import { useLocation,useNavigate } from "react-router-dom";
import './index.css'


const CommonTag = () => {
    const tabsList = useSelector(state => state.tab.tabList);
    const currentMenu = useSelector(state => state.tab.currentMenu);
    const dispatch=useDispatch();
    const action=useLocation();
    const navigate=useNavigate();
    const handleChange = (tag,index) => {
        dispatch(setCurrrentMenu(tag));
        navigate(tag.path);
    }
    const handleClose = (tag,index) => {
        let length=tabsList.length-1;
        dispatch(closeTab(tag))
      
        if(tag.path!==action.pathname)
        {
                return
        } 
 
        if(index===length)
        { 
            //设置当前数据
            const curData=tabsList[index-1];
            dispatch(setCurrrentMenu(curData));
            navigate(curData.path);
        }else
        {
          if(tabsList.length>1)
          {
            const nextData=tabsList[index+1];
            dispatch(setCurrrentMenu(nextData));
            navigate(nextData.path)
          }
        }
    }
    const setTag = (flag, item, index) => {
        return (
            flag ?
                <Tag key={item.name} color="#55acee" closeIcon onClose={()=>handleClose(item, index)}> {item.label}</Tag> :
                <Tag onClick={() => handleChange(item,index)} key={item.name}>{item.label}</Tag>
        )
    }
    return (
        <Space className="common-tag" size={[0, 8]} wrap>
            {/* <Tag color="#55acee"> 首页</Tag>  */}
            {currentMenu.name && tabsList.map((item, index) => (setTag(item.path === currentMenu.path, item, index)))}

        </Space>
    )
}
export default CommonTag